java


Arrays in Java: 1D and 2D Arrays

Arrays are one of the most fundamental data structures in Java. They allow you to store multiple values of the same type under a single variable name, making data handling easier and more efficient. In this blog, we will explore 1D arrays and 2D arrays in Java, along with examples.

What is an Array in Java?

An array is a container object that holds a fixed number of values of a single type. The elements of an array are stored in contiguous memory locations, and each element can be accessed using an index.

Key Characteristics of Arrays

Fixed size: Once declared, the size cannot change.

Homogeneous: All elements must be of the same data type.

Indexed: Elements are accessed using indices (starting from 0). 

One-Dimensional (1D) Arrays

datatype[] arrayName = new datatype[size];
 

Creating and Accessing a 1D Array

public class OneDArrayExample {
    public static void main(String[] args) {
        // Declare and initialize
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Access elements using index
        System.out.println("First element: " + numbers[0]);
        
        // Loop through array
        System.out.println("All elements:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
 

Two-Dimensional (2D) Arrays

A 2D array is like a table with rows and columns. It is essentially an array of arrays.

datatype[][] arrayName = new datatype[rows][columns];
datatype[][] arrayName = {
    {value1, value2},
    {value3, value4}
};

public class TwoDArrayExample {
    public static void main(String[] args) {
        // Declare and initialize
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // Access an element
        System.out.println("Element at (1,2): " + matrix[1][2]); // 6
        
        // Loop through 2D array
        System.out.println("Matrix elements:");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
 

Common Operations on Arrays Finding length: arrayName.length Iterating with enhanced for loop:

A 2D array is like a table with rows and columns. It is essentially an array of arrays.

//for loop for array.
for (int num : numbers) {
    System.out.println(num);
}

//Changing elements:
numbers[2] = 100; // changes third element


Advantages of Arrays:

Easy to access elements using index.

Efficient storage for multiple values.

Better performance for fixed-size data sets.



6. Limitations of Arrays

Fixed size — cannot grow or shrink dynamically.

All elements must be of the same type.

No built-in methods for advanced operations (sorting, searching) — requires manual coding or utility classes.